package com.geng.demo.util;

import cn.hutool.core.util.ObjectUtil;
import com.geng.demo.enums.ReturnMessageEnum;

import java.util.*;

public class ParamUtil {

    /**
     * 获取成功的返回空集合
     * 格式：
     * {
     *     "status":{
     *         "code":"000000",
     *         "message":"成功"
     *     }
     * }
     * @return
     */
    public static Map<String, Object> returnSuccessMap(){
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> status = new HashMap<>();
        status.put("code", ReturnMessageEnum.SUCCESS.getCode());
        status.put("message", ReturnMessageEnum.SUCCESS.getMessage());
        resultMap.put("status", status);
        return resultMap;
    }

    /**
     * 判断集合是否成功状态
     * status.code = 000000 则成功
     * @return
     */
    public static boolean isSuccess(Map<String, Object> map){
        if(ObjectUtil.isEmpty(map)){
            return false;
        }
        Map<String, Object> status = (Map<String, Object>)map.get("status");
        if(ObjectUtil.isEmpty(status)){
            return false;
        }
        String code = (String)status.get("code");  //信息码 000000-成功
        if(ObjectUtil.isEmpty(code)){
            return false;
        }
        return ObjectUtil.equal(code, ReturnMessageEnum.SUCCESS.getCode());
    }

    /**
     * 返回失败结果
     * @param returnMessageEnum 设置的码值
     */
    public static Map<String, Object> returnErrorMessage(ReturnMessageEnum returnMessageEnum){
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> status = new HashMap<>();
        status.put("code", returnMessageEnum.getCode());
        status.put("message", returnMessageEnum.getMessage());
        resultMap.put("status", status);
        return resultMap;
    }

    /**
     * 返回失败结果，自定义message
     * @param mesage
     * @return
     */
    public static Map<String, Object> returnErrorMessage(String mesage){
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> status = new HashMap<>();
        status.put("code", ReturnMessageEnum.FAIL.getCode());
        status.put("message", mesage);
        resultMap.put("status", status);
        return resultMap;
    }

    /**
     * 把数组所有元素排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串
     * @param params 需要排序并参与字符拼接的参数组
     * @return 拼接后字符串
     */
    public static String createLinkString(Map<String, String> params) {
        List<String> keys = new ArrayList<>(params.keySet());
        Collections.sort(keys);
        StringBuilder prestr = new StringBuilder();
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);
            if (i == keys.size() - 1) {// 拼接时，不包括最后一个&字符
                prestr.append(key).append("=").append(value);
            } else {
                prestr.append(key).append("=").append(value).append("&");
            }
        }
        return prestr.toString();
    }
}
